const fs = require("fs");
const path = require("path");
const type = require("./type");

function _mkDir(paths, prevPath){
  try{
    fs.existsSync(prevPath) || fs.mkdirSync(prevPath);
  } catch(e) {}
  paths.length && _mkDir(paths, `${prevPath}/${paths.shift()}`);
}
function mkDir(dirName) {
  if (!type.isString(dirName)) return;
  const paths = dirName.split(/[\\/]+/);
  _mkDir(paths, paths.shift());
}

function isFile(path) {return fs.statSync(path).isFile();}

function _readDir(dirPath, reg, result) { // path 读取的目录， reg 文件匹配的正则， result 为结果集
  const pathes = fs.readdirSync(dirPath);
  pathes.forEach(item => {
    const fullPath = path.join(dirPath, item);
    if (isFile(fullPath)) { // 判断是否为文件
      if (reg.test(item)) {
        result.push({ // 判断是否为指定文件
          path: dirPath + "/" + item, // 路径
          name: item.replace(reg, ""), // 文件名
        });
      }
    } else _readDir(dirPath + "/" + item, reg, result); // 文件夹的话 就往下读取
  })
}

function readDir(dirPath, reg) { // path 读取的目录， reg 文件匹配的正则 返回一个 读取完的数组
  const result = [];
  _readDir(dirPath, reg, result);
  return result;
}

function copyFile(oriPath, target){
  if (isFile(oriPath)) {
    fs.copyFileSync(oriPath, target)
  } else {
    mkDir(target);
    fs.readdirSync(oriPath).forEach(item => {
      copyFile(path.join(oriPath, item), path.join(target, item))
    })
  }
}

function toCamel(str = ""){
  str = str.replace(/^[\\/]/, "").replace(/[\\/]+/, " ").replace(paramReplaceReg, "").replace(/{[^{}]+}/g, " ");
  while (splitReg.test(str)) {
    str = str.replace(splitReg, function () {
      return arguments[0][1].toUpperCase();
    })
  }
  return str;
}


function camel(str = '') {
  return {
    large: str.replace(/-[a-zA-z]/g, a => a[1].toUpperCase()).replace(/./, a => a.toUpperCase()),
    small: str.replace(/-[a-zA-z]/g, a => a[1].toUpperCase()).replace(/./, a => a.toLowerCase()),
    self: str,
    _large: str.replace(/-[a-zA-z]/g, a => `_${a[1].toUpperCase()}`).replace(/./, a => a.toUpperCase()),
    _self: str.replace(/-/g, '_'),
  }
}

function _deepReadDir(dirPath, reg) { // path 读取的目录， reg 文件匹配的正则， result 为结果集
  const pathes = fs.readdirSync(dirPath);
  return pathes.map(item => {
    const fullPath = path.join(dirPath, item);
    if (!isFile(fullPath)) { // 判断是否不为文件
      if (reg.test(item)) {
        const param = camel(item.replace(reg, ''))
        // console.log(param)
        return {
          id: '32',
          // id: param.self,
          meta: {title: ''},
          path: `${param.self}`,
          name: param.self,
          component: `() => import('${fullPath.replace(/^src/, '@').replace(/\\/g, '/')}/${param._large}.vue')`,
          children: _deepReadDir(dirPath + "/" + item, reg)
        }
      }
    }
  }).filter(item => item)
}

function deepReadDir(dirPath, reg) { // path 读取的目录， reg 文件匹配的正则 返回一个 读取完的数组
  return _deepReadDir(dirPath, reg);
}


module.exports = {
  mk: mkDir,
  readFileInType: readDir,
  deepReadDir: deepReadDir,
  copy: copyFile
};
